package org.ym.tools.adapter;

import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonToken;
import com.google.gson.stream.JsonWriter;
import org.apache.commons.lang3.StringUtils;
import org.ym.tools.NumberTool;
import org.ym.tools.StringTool;

import java.io.IOException;

/**
 * @author ym
 */
public class LongJsonAdapter extends TypeAdapter<Long> {
    @Override
    public void write(JsonWriter jsonWriter, Long s) throws IOException {
        jsonWriter.value(StringTool.objectToString(s));
    }

    @Override
    public Long read(JsonReader jsonReader) throws IOException {
        if(jsonReader.peek() == JsonToken.NULL){
            jsonReader.nextNull();
            return null;
        }
        String value = jsonReader.nextString();
        if(StringUtils.isBlank(value)){
            return null;
        }
        return NumberTool.parseLong(value);
    }
}
